package com.mzl.lal4cloud.lxw4rf.service.contract.config;

import com.mzl.lal4cloud.lxw4rf.service.contract.bean.AccessToken;
import com.mzl.lal4cloud.lxw4rf.service.contract.bean.HostConfig;
import lombok.Data;

import java.io.Serializable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author J_luo
 */
@Data
public class DefaultConfigStorage implements ConfigStorage, Serializable {

    /**
     * 令牌id
     */
    protected volatile String clientId;

    /**
     * 令牌码
     */
    protected volatile String clientSecret;

    /**
     * 私钥
     */
    protected volatile String privateKey;

    /**
     * 授权token
     */
    protected volatile String accessToken;

    /**
     * 失效时间
     */
    protected volatile long expiresTime;

    protected volatile Lock accessTokenLock = new ReentrantLock();

    protected volatile String httpProxyHost;
    protected volatile int httpProxyPort;
    protected volatile String httpProxyUsername;
    protected volatile String httpProxyPassword;

    private HostConfig hostConfig = null;

    /**
     * Is access token expired boolean.
     *
     * @return the boolean
     */
    @Override
    public boolean isAccessTokenExpired() {
        return System.currentTimeMillis() > this.expiresTime;
    }

    /**
     * 强制将access token过期掉.
     */
    @Override
    public void expireAccessToken() {
        this.expiresTime = 0;
    }

    /**
     * 应该是线程安全的.
     *
     * @param accessToken 要更新的WxAccessToken对象
     */
    @Override
    public void updateAccessToken(AccessToken accessToken) {
        updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
    }

    /**
     * 应该是线程安全的.
     *
     * @param accessToken      新的accessToken值
     * @param expiresInSeconds 过期时间，以秒为单位
     */
    @Override
    public void updateAccessToken(String accessToken, int expiresInSeconds) {
        this.accessToken = accessToken;
        this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
    }

    /**
     * 是否自动刷新token.
     *
     * @return the boolean
     */
    @Override
    public boolean autoRefreshToken() {
        return true;
    }

    @Override
    public HostConfig getHostConfig() {
        return this.hostConfig;
    }


    @Override
    public void setHostConfig(HostConfig hostConfig) {
        this.hostConfig = hostConfig;
    }
}
